//
//  TSMainDetailViewController.swift
//  TSProfitProject
//
//  Created by TMS on 2019/11/15.
//  Copyright © 2019 TMS. All rights reserved.
//

import UIKit

private let countdownSecond = 15

class TSMainDetailViewController: TSBaseViewController {
    
    var identifier : String!
    
    private var countDownTimer : DispatchSourceTimer?
    private var isFirstLoad : Bool = true
    
    private var model : TSMainPageModel!
    
    lazy var dataSource : [TSRecordModel] = []
    
    var tableController : TSBaseTableViewController!
    
    lazy var footerView : TSProfitFooterView = {
        var footer = TSProfitFooterView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 40))
        footer.delegate = self
        return footer
    }()
    
    lazy var recordAlert : TSDetailRecordAlertView = {
        var record = TSDetailRecordAlertView.init(frame: UIScreen.main.bounds)
        record.delegate = self
        record.isHidden = true
        return record
    }()
    
    lazy var detailAlert : TSRecordAlertView = {
        var detail = TSRecordAlertView.init(frame: UIScreen.main.bounds)
        detail.isHidden = true
        return detail
    }()
    
    lazy var preInvestView : TSPreInvestView = {
        var investView = TSPreInvestView.init(frame: UIScreen.main.bounds)
        investView.delegate = self
        investView.isHidden = true
        return investView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let str = NSString.init(string: identifier == OYMultipleTableSource1 ? "北京赛车" : "幸运飞艇")
        setupNavigationTitle(title: str.components(separatedBy: " ").first!)
        configViews()
        
        self.requestTicketInfo(identifier: identifier) { (isSuccess) in
            
            self.isFirstLoad = false
            
            if isSuccess {
                
                DispatchQueue.main.async {
                    OYCountDownManager.sharedManager.addSourceWithIdentifier(identifier: self.model.identifier)
                   
                    self.tableController.tableView .reloadData()
                   
                    OYCountDownManager.sharedManager.start()
                    
                }
            } else {
                CBToast.hiddenToastAction()
            }
        }
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        if countDownTimer != nil {
            countDownTimer!.cancel()
        }
    }
    
    deinit {

        OYCountDownManager.sharedManager.invalidate()
        OYCountDownManager.sharedManager.removeAllSource()
    }
}

//MARK: - TSPreInvestViewDelegate
extension TSMainDetailViewController : TSPreInvestViewDelegate {
    func preCompleteInvest(_ args: (Array<String>, String, String)) {
        getInvest(args)
    }
}

//MARK: - TSProfitFooterViewDelegate
extension TSMainDetailViewController : TSProfitFooterViewDelegate {
    func completeInvest(_ args: (Array<String>, String, String)) {
//        getInvest(args)
        
        preInvestView.setupView(args: args)
        preInvestView.isHidden = false
    }
    
    func didClickRecord() {
        recordAlert.isHidden = false
        self.requestRecordDatas(type: self.model.title == "幸运飞艇 5分钟一期" ? "1" : "2", showHud: true)
    }
}

//MARK: - TSDetailRecordAlertViewDelegate
extension TSMainDetailViewController : TSDetailRecordAlertViewDelegate {
    
    func tradeWillBeRevoke(id: String) {
        revokeOrder(id: id)
    }
    
    func scanRecordDetail(model: TSRecordModel) {
        detailAlert.setupView(model: model)
        detailAlert.isHidden = false
    }

}

//MARK: - TSProfitResultTableViewCellDelegate
extension TSMainDetailViewController : TSProfitResultTableViewCellDelegate {
    
    func countdownEnd(model: TSMainPageModel) {
        
        if self.model.countdownFinished {
            return
        }
        
        self.model = model
        
        countdownStart()
    }
    
    func countdownStart() {

        TSLog("开启倒计时,20s后请求接口")
        weak var WeakSelf = self

        var timeout = countdownSecond
        let queue = DispatchQueue.global()
        let timer = DispatchSource.makeTimerSource(flags: .init(rawValue: 0), queue: queue)
        countDownTimer = timer
        countDownTimer!.schedule(deadline: .now(), repeating:  .milliseconds(1000))
        countDownTimer!.setEventHandler {
            timeout = timeout - 1
            if timeout < 0 {
                DispatchQueue.main.async {
                    
                    self.requestTicketInfo(identifier: self.identifier) { (isSuccess) in
                        
                        if isSuccess {
                            OYCountDownManager.sharedManager.reloadSourceWithIdentifier(identifier: OYMultipleTableSource1)
                            WeakSelf?.tableController.tableView.reloadData()
                        }
                    }
                }
                WeakSelf?.countDownTimer!.cancel()
            }
        }
        if #available(iOS 10.0, *) {
            countDownTimer!.activate()
        } else {
            countDownTimer!.resume()
        }
    }
}

//MARK: - UITableViewDelegate
extension TSMainDetailViewController : UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        10
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 10))
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        if section == 1 {
            return self.footerView
        }
        
        return UIView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 0.001))
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        section == 1 ? 430 : 0.001
    }
}

//MARK: - UITableViewDataSource
extension TSMainDetailViewController : UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return self.model != nil ? 2 : 0
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell : UITableViewCell?
        
        if indexPath.section == 0 {
            
            var profitCell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(TSProfitTableViewCell.self)) as? TSProfitTableViewCell
            
            if profitCell == nil {
                profitCell = TSProfitTableViewCell.init(style: .default, reuseIdentifier: NSStringFromClass(TSProfitTableViewCell.self))
            }
            
            profitCell?.refreshCell()
            
            cell = profitCell
            
        } else {
            
            var resultCell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(TSProfitResultTableViewCell.self)) as? TSProfitResultTableViewCell
            
            if resultCell == nil {
                resultCell = TSProfitResultTableViewCell.init(style: .default, reuseIdentifier: NSStringFromClass(TSProfitResultTableViewCell.self))
            }
            
            resultCell?.delegate = self
            
            resultCell?.setupCell(model: model)
            
            cell = resultCell
        }
        
        return cell!
    }
    
}

//MARK: - Network Request
extension TSMainDetailViewController {
    
    /** 投注记录 */
    func requestRecordDatas(type:String, showHud:Bool) {

        if showHud {
            CBToast.showToastAction()
        }
        TSNetworkManager.request(TMSNetworkTools.getInvsetRecord(type: type), showHUD: true, success: { (data) in
            
            CBToast.hiddenToastAction()
            
            self.dataSource.removeAll()
            
            let array = data as? Array<Dictionary<String, Any>>
            if array?.count ?? 0 > 0 {
                for item in array! {
                    let tempModel = TSRecordModel.deserialize(from: item)
                    if let model = tempModel {
                        self.dataSource.append(model)
                    }
                }
            }
            self.recordAlert.dataSource = self.dataSource
        }) { (error) in
            CBToast.hiddenToastAction()
        }
    }
    
    /** 撤单 */
    func revokeOrder(id:String) {
        
        CBToast.showToastAction()
        TSNetworkManager.request(TMSNetworkTools.revokeOrder(id: id), showHUD: true, success: { (data) in
            CBToast.hiddenToastAction()
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.5) {
                CBToast.showToastAction(message: "撤单成功")
            }
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1) {
                self.requestRecordDatas(type: self.model.title == "幸运飞艇 5分钟一期" ? "1" : "2", showHud: true)
            }
            
        }) { (error) in
            CBToast.hiddenToastAction()
        }
    }
    
    /** 下注 */
    func getInvest(_ args: (Array<String>, String, String)) {

        let array = args.0
        
        CBToast.showToastAction()
        TSNetworkManager.request(TMSNetworkTools.getInvest(qihao: "\(model.current)", jizhu: args.1, qufen: model.title == "幸运飞艇 5分钟一期" ? 1 : 2, one: array[0], two: array[1], three: array[2], four: "100", mingci: args.2), showHUD: true, success: { (data) in

            CBToast.hiddenToastAction()
            self.footerView.resetState()
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.5) {
                CBToast.showToastAction(message: "投注成功")
            }
            self.requestUserInfo()
            self.requestRecordDatas(type: self.model.title == "幸运飞艇 5分钟一期" ? "1" : "2", showHud: false)

        }) { (error) in
            
            CBToast.hiddenToastAction()
            
        }
    }
    
    /** 刷新用户信息 */
    func requestUserInfo() {
        
        TSNetworkManager.request(TMSNetworkTools.getUserInfo, showHUD: true, success: { (data) in
            
            let responseDic = data as? NSDictionary
            var model = TSLoginModel.deserialize(from: responseDic)!
            model.token = TSLoginManager.shared.token
            model.user_id = TSLoginManager.shared.user_id
            TSLoginManager.shared.setUserModel(model: model)
            
            self.tableController.tableView.reloadData()
            
        }) { (error) in
            
        }
    }
    
    /** 获取彩票详情信息 */
    private func requestTicketInfo(identifier:String, complete completeCallback: @escaping(_ isSuccess:Bool) -> Void) {
        
        if isFirstLoad {
            CBToast.showToastAction()
        }
        var target : TMSNetworkTools!
        if identifier == OYMultipleTableSource1 {
            target = TMSNetworkTools.getRacingInfo
        } else {
            target = TMSNetworkTools.getYachtInfo
        }
        
        TSNetworkManager.request(target, showHUD: true, success: { (data) in
            
//            TSLog(data)

            let responseDic = data as? NSDictionary
            self.model = TSMainPageModel.deserialize(from: responseDic)
            
            if self.model != nil {
                let date = Date.stringConvertDate(string: self.model.currentTime, dateFormat: "yyyy-MM-dd HH:mm:ss")
                let timeInterval = Date.getTimeDifferentWith(date: date)
                
                if timeInterval < 0 {
                    self.model.interval = abs(timeInterval)
                } else {
                    self.model.interval = 0
                }
                self.model.title = identifier == OYMultipleTableSource1 ? "北京赛车 20分钟一期" : "幸运飞艇 5分钟一期"
                self.model.identifier = identifier
                
                self.requestRecordDatas(type: self.model.title == "幸运飞艇 5分钟一期" ? "1" : "2", showHud: false)
                
                completeCallback(true)
                
            } else {
                
                CBToast.showIndicatorToastAction(message: "信息获取失败，请稍后再试")
                if self.isFirstLoad {
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                        self.navigationController?.popViewController(animated: true)
                    }
                } else {
                    self.countdownStart()
                }
                completeCallback(false)
            }

        }) { (error) in
            
            if self.isFirstLoad {
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
                    self.navigationController?.popViewController(animated: true)
                }
            } else {
                self.countdownStart()
            }
            
            completeCallback(false)
        }
    }
}

//MARK: - Initialize
extension TSMainDetailViewController {
    
    func configViews() {
        
        tableController = TSBaseTableViewController.init(style: .grouped)
        tableController.shouldDisplayEmptyAlert = true
        tableController.tableView.delegate = self
        tableController.tableView.dataSource = self
        tableController.tableView.showsVerticalScrollIndicator = false
        tableController.tableView.separatorStyle = .none
        tableController.tableView.estimatedRowHeight = 100
        tableController.tableView.rowHeight = UITableView.automaticDimension
        view.addSubview(tableController.tableView)
        tableController.tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(T_NAVBARHEIGHT)
        }
        
        UIApplication.shared.keyWindow!.addSubview(recordAlert)
        UIApplication.shared.keyWindow!.addSubview(detailAlert)
        UIApplication.shared.keyWindow!.addSubview(preInvestView)
    }
}
